/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.IllegalOrphanException;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Gallery;
import shmallarchitect.jpa.entities.User;
import shmallarchitect.jpa.entities.Owner;
import shmallarchitect.jpa.entities.Locum;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;

/**
 *
 * @author jaccus
 */
public class GalleryJpaController {
    @Resource(mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Gallery gallery) throws RollbackFailureException, Exception {
        if (gallery.getLocums() == null) {
            gallery.setLocums(new HashSet<Locum>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User user = gallery.getUser();
            if (user != null) {
                user = em.getReference(user.getClass(), user.getId());
                gallery.setUser(user);
            }
            Owner owner = gallery.getOwner();
            if (owner != null) {
                owner = em.getReference(owner.getClass(), owner.getId());
                gallery.setOwner(owner);
            }
            Set<Locum> attachedLocums = new HashSet<Locum>();
            for (Locum locumsLocumToAttach : gallery.getLocums()) {
                locumsLocumToAttach = em.getReference(locumsLocumToAttach.getClass(), locumsLocumToAttach.getId());
                attachedLocums.add(locumsLocumToAttach);
            }
            gallery.setLocums(attachedLocums);
            em.persist(gallery);
            if (user != null) {
                user.getGalleries().add(gallery);
                user = em.merge(user);
            }
            if (owner != null) {
                owner.getGalleries().add(gallery);
                owner = em.merge(owner);
            }
            for (Locum locumsLocum : gallery.getLocums()) {
                Gallery oldGalleryOfLocumsLocum = locumsLocum.getGallery();
                locumsLocum.setGallery(gallery);
                locumsLocum = em.merge(locumsLocum);
                if (oldGalleryOfLocumsLocum != null) {
                    oldGalleryOfLocumsLocum.getLocums().remove(locumsLocum);
                    oldGalleryOfLocumsLocum = em.merge(oldGalleryOfLocumsLocum);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Gallery gallery) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Gallery persistentGallery = em.find(Gallery.class, gallery.getId());
            User userOld = persistentGallery.getUser();
            User userNew = gallery.getUser();
            Owner ownerOld = persistentGallery.getOwner();
            Owner ownerNew = gallery.getOwner();
            Set<Locum> locumsOld = persistentGallery.getLocums();
            Set<Locum> locumsNew = gallery.getLocums();
            List<String> illegalOrphanMessages = null;
            for (Locum locumsOldLocum : locumsOld) {
                if (!locumsNew.contains(locumsOldLocum)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Locum " + locumsOldLocum + " since its gallery field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (userNew != null) {
                userNew = em.getReference(userNew.getClass(), userNew.getId());
                gallery.setUser(userNew);
            }
            if (ownerNew != null) {
                ownerNew = em.getReference(ownerNew.getClass(), ownerNew.getId());
                gallery.setOwner(ownerNew);
            }
            Set<Locum> attachedLocumsNew = new HashSet<Locum>();
            for (Locum locumsNewLocumToAttach : locumsNew) {
                locumsNewLocumToAttach = em.getReference(locumsNewLocumToAttach.getClass(), locumsNewLocumToAttach.getId());
                attachedLocumsNew.add(locumsNewLocumToAttach);
            }
            locumsNew = attachedLocumsNew;
            gallery.setLocums(locumsNew);
            gallery = em.merge(gallery);
            if (userOld != null && !userOld.equals(userNew)) {
                userOld.getGalleries().remove(gallery);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld)) {
                userNew.getGalleries().add(gallery);
                userNew = em.merge(userNew);
            }
            if (ownerOld != null && !ownerOld.equals(ownerNew)) {
                ownerOld.getGalleries().remove(gallery);
                ownerOld = em.merge(ownerOld);
            }
            if (ownerNew != null && !ownerNew.equals(ownerOld)) {
                ownerNew.getGalleries().add(gallery);
                ownerNew = em.merge(ownerNew);
            }
            for (Locum locumsNewLocum : locumsNew) {
                if (!locumsOld.contains(locumsNewLocum)) {
                    Gallery oldGalleryOfLocumsNewLocum = locumsNewLocum.getGallery();
                    locumsNewLocum.setGallery(gallery);
                    locumsNewLocum = em.merge(locumsNewLocum);
                    if (oldGalleryOfLocumsNewLocum != null && !oldGalleryOfLocumsNewLocum.equals(gallery)) {
                        oldGalleryOfLocumsNewLocum.getLocums().remove(locumsNewLocum);
                        oldGalleryOfLocumsNewLocum = em.merge(oldGalleryOfLocumsNewLocum);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = gallery.getId();
                if (findGallery(id) == null) {
                    throw new NonexistentEntityException("The gallery with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Gallery gallery;
            try {
                gallery = em.getReference(Gallery.class, id);
                gallery.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The gallery with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Set<Locum> locumsOrphanCheck = gallery.getLocums();
            for (Locum locumsOrphanCheckLocum : locumsOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Gallery (" + gallery + ") cannot be destroyed since the Locum " + locumsOrphanCheckLocum + " in its locums field has a non-nullable gallery field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            User user = gallery.getUser();
            if (user != null) {
                user.getGalleries().remove(gallery);
                user = em.merge(user);
            }
            Owner owner = gallery.getOwner();
            if (owner != null) {
                owner.getGalleries().remove(gallery);
                owner = em.merge(owner);
            }
            em.remove(gallery);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Gallery> findGalleryEntities() {
        return findGalleryEntities(true, -1, -1);
    }

    public List<Gallery> findGalleryEntities(int maxResults, int firstResult) {
        return findGalleryEntities(false, maxResults, firstResult);
    }

    private List<Gallery> findGalleryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Gallery as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Gallery findGallery(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Gallery.class, id);
        } finally {
            em.close();
        }
    }

    public int getGalleryCount() {
        EntityManager em = getEntityManager();
        try {
            final Query createQuery = em.createQuery("select count(o) from Gallery as o");
            final Object singleResult = createQuery.getSingleResult();
            final Long name = (Long) singleResult;
            final int intValue = name.intValue();
            return intValue;
        } catch (Throwable e) {
            e.printStackTrace();
          return 0;

        } finally {
            em.close();
        }
    }

}
